<template>
	<div>
		<el-upload :http-request="upload" :before-upload="beforeUpload" :limit="limit" :on-remove="handleRemove"
			:on-change="handleChange" :class="{disabled: fileComputed }" list-type="picture-card" :file-list="fileList"
			:on-preview="preview" action="#">
			<i class="el-icon-plus" />
		</el-upload>

		<el-dialog title="图片" :visible.sync="showDialog">
			<img :src="imgUrl" style="width:100%" alt="">
		</el-dialog>

		<el-progress v-if="showPercent" style="width: 180px" :percentage="percent" />
	</div>
</template>

<script>
	import COS from 'cos-js-sdk-v5'
	
	var cos = new COS({
		SecretId: 'AKIDKTLyLSIyOXPjna5JHyOWNyIK5apnUv5y', // 身份识别 ID
		SecretKey: 'd3C4fy1nHUQ5TaS3NQCixua08zYrsc5x', // 身份密钥
	});
	
	export default {
		props: {
			limit: {
				default: 1,
				type: Number
			}
		},

		data() {
			return {
				fileList: [], // 图片地址设置为数组 
				showDialog: false, // 控制显示弹层
				imgUrl: '',
				showPercent: false,
				percent: 0
			}
		},

		computed: {
			fileComputed() {
				return this.fileList.length === this.limit
			}
		},

		methods: {
			preview(file) {
				// 这里应该弹出一个层 层里是点击的图片地址
				this.imgUrl = file.url
				this.showDialog = true
			},

			handleRemove(file) {
				this.fileList = this.fileList.filter(item => item.uid !== file.uid)
			},

			handleChange(file, fileList) {
				this.fileList = fileList.map(item => item)
			},

			beforeUpload(file) {
				const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
				if (!types.includes(file.type)) {
					this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
					return false
				}
				const maxSize = 5 * 1024 * 1024
				if (maxSize < file.size) {
					this.$message.error('图片大小最大不能超过5M')
					return false
				}
				return true
			},

			upload(params) {
				if (params.file) {
					this.showPercent = true
					// 执行上传操作
					cos.putObject({
						Bucket: 'hrsaas-1305172101', // 存储桶
						Region: 'ap-nanjing', // 地域
						Key: params.file.name, // 文件名
						Body: params.file, // 要上传的文件对象
						StorageClass: 'STANDARD',
						onProgress: params => {
							this.percent = params.percent * 100
						}
					}, (err, data) => {
						if (!err && data.statusCode === 200) {
							this.fileList = this.fileList.map(item => {
								// 去找谁的uid等于刚刚记录下来的id
								if (item.uid === params.file.uid) {
									return {
										url: 'http://' + data.Location,
										status: 'success'
									}
								}
								return item
							})
							setTimeout(() => {
								this.showPercent = false
								this.percent = 0
							}, 500)
						}
					})
				}
			},
		}
	}
</script>

<style scoped>
	.disabled .el-upload--picture-card {
		display: none
	}
</style>
